namespace Sustainalytics.ReportGenerator.BL
{
    using System;
    using System.Collections.Concurrent;
    using System.IO;
    using System.IO.Compression;
    using System.Linq;
    using System.Net.Mail;
    using System.Net.Mime;
    using System.Text;

    using Sustainalytics.Utils.Configuration;

    public class PdfEmailLogger:ILogPdf
    {
        private readonly ConcurrentQueue<string> _queueLog;

        public PdfEmailLogger()
        {
            this._queueLog = new ConcurrentQueue<string>();
        }

        public void LogGenerationData(string msg)
        {
            this._queueLog.Enqueue(string.Format("{0}:{1}",DateTime.UtcNow.ToString("T"),msg));
        }


        public void SendEmailLog(string subject)
        {
            var support = SettingsHelper.Read("SupportEmail", "platformsupport@sustainalytics.com");
            var sb=new StringBuilder();
            foreach (var data in this._queueLog)
            {
                sb.AppendLine(data);
            }
            SendEmail(new[] { support }, null, subject, sb.ToString(), false, false, "", new byte[0]);
        }


        private static void SendEmail(string[] recipients, string[] replyTo, string subject, string body,
                                      bool isBodyHtml, bool hasAttachment, string attachmentName, byte[] attachmentContent)
        {
            if (subject == null || body == null) return;

            var mail = new MailMessage();

            var from = SettingsHelper.Read("SMTPUserName", "platform@sustainalytics.com");

            mail.From = new MailAddress(@from);
            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = isBodyHtml;
            var attachmentArchivingThresholdKb = int.Parse(SettingsHelper.Read("AttachmentArchivingThresholdKB", "500"));

            if (recipients != null && recipients.Any())
            {
                mail.To.Clear();

                for (var i = 0; i < recipients.Count(); i++)
                {
                    mail.To.Add(new MailAddress(recipients.ElementAt(i)));
                }
            }

            if (replyTo != null && replyTo.Any())
            {
                mail.CC.Clear();

                for (var i = 0; i < replyTo.Count(); i++)
                {
                    mail.CC.Add(new MailAddress(replyTo.ElementAt(i)));
                }
            }

            if (hasAttachment)
            {
                var contentType = new ContentType
                                      {
                                          Name = attachmentName,
                                          MediaType = MediaTypeNames.Application.Octet
                                      };

                if (attachmentContent.Length > attachmentArchivingThresholdKb * 1024) // compress attachments larger than the set archiving threshold
                {
                    var archivingFolder = Directory.CreateDirectory("ArchivingDir");

                    File.WriteAllBytes(Path.Combine(archivingFolder.Name, contentType.Name), attachmentContent);
                    contentType.Name += ".zip";

                    ZipFile.CreateFromDirectory(archivingFolder.Name, contentType.Name);// GZipStream/DeflateStream does not provide a way to include a file name in the header of the zipped stream

                    attachmentContent = File.ReadAllBytes(contentType.Name);
                    archivingFolder.Delete(true);
                    File.Delete(contentType.Name);
                }

                mail.Attachments.Add(new Attachment(new MemoryStream(attachmentContent), contentType));
            }

            var smtpClient = new SmtpClient(SettingsHelper.Read("SMTPServer", "pod51017.outlook.com"))
                                 {
                                     Port = int.Parse(SettingsHelper.Read("SMTPServerPort", "587")),
                                     Credentials =
                                         new System.Net.NetworkCredential(
                                         SettingsHelper.Read("SMTPUserName", "platform@sustainalytics.com"),
                                         SettingsHelper.Read("SMTPPassword", "Password99#")),
                                     EnableSsl = true
                                 };

            smtpClient.Send(mail);
        }
    }
}